package net.piggy.config.security;


import net.piggy.config.security.filter.TokenVerifyFilter;
import net.piggy.config.security.handler.PiggyLogoutHandler;
import net.piggy.config.security.provider.LoginAuthenticationProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.annotation.Resource;


@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Resource
	private LoginAuthenticationProvider loginProvider;
	@Resource
	private PiggyLogoutHandler piggyLogoutHandler;

	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				// 认证通过 授权不通过
//				.antMatchers("").permitAll()
				.anyRequest().authenticated().and()
				.addFilterBefore(new TokenVerifyFilter(), UsernamePasswordAuthenticationFilter.class)
				.csrf().disable()
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
				.logout().logoutUrl("/logout").logoutSuccessHandler(piggyLogoutHandler);

	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) {
		auth.authenticationProvider(loginProvider);
		auth.authenticationEventPublisher(new AuthenticationEventPublisher() {
			@Override
			public void publishAuthenticationSuccess(Authentication authentication) {

			}

			@Override
			public void publishAuthenticationFailure(AuthenticationException exception, Authentication authentication) {

			}
		});
	}

	@Override
	public void configure(WebSecurity web) {
		// 认证通过 授权通过
		web.ignoring().antMatchers("/login","/picture/**","/favicon.ico");
	}
}
